<template>
	<n-modal v-model:show="modalVisible" preset="card" :title="title" class="w-800px">
		<n-form ref="formRef" label-placement="left" :label-width="100" :model="formModel" :rules="rules">
			<n-form-item label="角色" path="operator_role_id">
				<n-radio-group v-model:value="formModel.operator_role_id" name="radiogroup">
					<n-space>
						<n-radio :value="1">超级管理员</n-radio>
						<n-radio :value="2">分销商</n-radio>
						<n-radio :value="3">联运商</n-radio>
					</n-space>
				</n-radio-group>
			</n-form-item>
			<n-grid :cols="3">
				<n-form-item-grid-item label="用户名" path="username">
					<n-input v-model:value="formModel.username" />
				</n-form-item-grid-item>
				<n-form-item-grid-item label="手机号" path="mobile">
					<n-input v-model:value="formModel.mobile"/>
				</n-form-item-grid-item>
				<n-form-item-grid-item label="密码" path="password">
					<n-input v-model:value="formModel.password" type="password"/>
				</n-form-item-grid-item>
			</n-grid>
			<n-grid :cols="3">
				<n-form-item-grid-item label="营业执照" path="username">
					<n-upload :action="`${url}/admin/Tools/upload`" :headers="uploadHeaderDate" :data="uploadDate"
						list-type="image-card" :max="1" @finish="onFinish1" @remove="onRemove1">
						<img v-if="formModel.business_license_pic" :src="formModel.business_license_pic" style="width: 100%">
					</n-upload>
				</n-form-item-grid-item>
				<n-form-item-grid-item label="身份证正面" path="username">
					<n-upload :action="`${url}/admin/Tools/upload`" :headers="uploadHeaderDate" :data="uploadDate"
						list-type="image-card" :max="1" @finish="onFinish2" @remove="onRemove2">
						<img v-if="formModel.id_card_front_pic" :src="formModel.id_card_front_pic" style="width: 100%">
					</n-upload>
				</n-form-item-grid-item>
				<n-form-item-grid-item label="身份证背面" path="username">
					<n-upload :action="`${url}/admin/Tools/upload`" :headers="uploadHeaderDate" :data="uploadDate"
						list-type="image-card" :max="1" @finish="onFinish3" @remove="onRemove3">
						<img v-if="formModel.id_card_back_pic" :src="formModel.id_card_back_pic" style="width: 100%">
					</n-upload>
				</n-form-item-grid-item>
			</n-grid>
			<n-form-item label="其他资料">
				<n-upload :action="`${url}/admin/Tools/upload`" :headers="uploadHeaderDate" :data="uploadDate"
					list-type="image-card" :max="1" @finish="onFinish4" @remove="onRemove4">
					<img v-if="formModel.information_pic" :src="formModel.information_pic" style="width: 100%">
				</n-upload>
			</n-form-item>
			<n-space class="w-full pt-16px" :size="24" justify="end">
				<n-button class="w-72px" @click="closeModal">取消</n-button>
				<n-button class="w-72px" type="primary" @click="handleSubmit">确定</n-button>
			</n-space>
		</n-form>
	</n-modal>
</template>

<script setup lang="ts">
import { ref, computed, reactive, watch } from 'vue';
import type { FormInst, FormItemRule, UploadFileInfo } from 'naive-ui';
import { addOperator, updateOperator } from '@/service';
import { formRules, createRequiredFormRule, localStg } from '@/utils';
import { getServiceEnvConfig } from '~/.env-config';

export interface Props {
	/** 弹窗可见性 */
	visible: boolean;
	/**
	 * 弹窗类型
	 * add: 新增
	 * edit: 编辑
	 */
	type?: 'add' | 'edit';
	/** 编辑的表格行数据 */
	editData?: any;
}

export type ModalType = NonNullable<Props['type']>;

const { url } = getServiceEnvConfig(import.meta.env);

defineOptions({ name: 'TableActionModal' });

const props = withDefaults(defineProps<Props>(), {
	type: 'add',
	editData: null
});

interface Emits {
	(e: 'update:visible', visible: boolean): void;
	(e: 'refresh'): void;
}

const emit = defineEmits<Emits>();

const modalVisible = computed({
	get() {
		return props.visible;
	},
	set(visible) {
		emit('update:visible', visible);
	}
});
// 关闭弹框
const closeModal = () => {
	modalVisible.value = false;
};

// 组件标题
const title = computed(() => {
	const titles: Record<ModalType, string> = {
		add: '添加用户',
		edit: '编辑用户'
	};
	return titles[props.type];
});

const formRef = ref<HTMLElement & FormInst>();

type FormModel = any;
const formModel = reactive<FormModel>(createDefaultFormModel());

const rules: Record<keyof FormModel, FormItemRule | FormItemRule[]> = {
	username: createRequiredFormRule('请输入用户名'),
	mobile: formRules.phone,
	operator_role_id: createRequiredFormRule('请选择角色'),
	password: formRules.pwd,
	business_license_pic: createRequiredFormRule('请上传营业执照'),
	id_card_front_pic: createRequiredFormRule('请上传身份证正面'),
	id_card_back_pic: createRequiredFormRule('请上传身份证背面')
};

function createDefaultFormModel(): FormModel {
	return {
		username: '',// 用户名
		mobile: '', // 手机号
		operator_role_id: null, // 角色id
		password: '', // 密码
		business_license_pic: '', // 营业执照
		id_card_front_pic: '', // 法人身份证正面
		id_card_back_pic: '', // 法人身份证背面
		information_pic: '', // 其他资料
	};
}

function handleUpdateFormModel(model: Partial<FormModel>) {
	Object.assign(formModel, model);
}

function handleUpdateFormModelByModalType() {
	const handlers: Record<ModalType, () => void> = {
		add: () => {
			const defaultFormModel = createDefaultFormModel();
			handleUpdateFormModel(defaultFormModel);
		},
		edit: () => {
			if (props.editData) {
				handleUpdateFormModel(props.editData);
			}
		}
	};
	handlers[props.type]();
}
// 添加/删除
async function handleSubmit() {
	await formRef.value?.validate();
	const err = await formRef.value?.validate();
	if (!err) {
		console.log(props.type);
		if (props.type === 'add') {
			const res: any = await addOperator(formModel);
			if (res.code === 0) {
				window.$message?.success('新增成功!');
				closeModal();
				emit('refresh');
			}
		} else {
			const res: any = await updateOperator(formModel);
			if (res.code === 0) {
				window.$message?.success('修改成功!');
				closeModal();
				emit('refresh');
			}
		}
	}
}


// 上传图片...
const uploadHeaderDate: any = { //header
	token: localStg.get('token')
}
const uploadDate = { // params
	group: 'user'
}
// 上传成功的回调
function onFinish1(file: any) {
	// console.log(JSON.parse(file.event.target.response).data.pic_full_url);
	formModel.business_license_pic = JSON.parse(file.event.target.response).data.pic_full_url
}
function onFinish2(file: any) {
	formModel.id_card_front_pic = JSON.parse(file.event.target.response).data.pic_full_url
}
function onFinish3(file: any) {
	formModel.id_card_back_pic = JSON.parse(file.event.target.response).data.pic_full_url
}
function onFinish4(file: any) {
	formModel.information_pic = JSON.parse(file.event.target.response).data.pic_full_url
}
// 移除上传的回调
function onRemove1() {
	formModel.business_license_pic = ""
}
function onRemove2() {
	formModel.id_card_front_pic = ""
}
function onRemove3() {
	formModel.id_card_back_pic = ""
}
function onRemove4() {
	formModel.information_pic = ""
}

watch(
	() => props.visible,
	newValue => {
		if (newValue) {
			handleUpdateFormModelByModalType();
		}
	}
);
</script>

<style scoped></style>
